package com.jhws.core.shiro.filter;

import com.jhws.business.comm.bo.TblCommDimBo;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.business.comm.service.ITblCommDimService;
import com.jhws.sys.appUser.service.ITblSipAcountDimService;
import com.jhws.util.jsonUtil;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.MediaType;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 本地服务器调用的相关同步接口所用的拦截器
 * Created by Administrator on 2017/3/31.
 */
public class LocalSrvFilter extends PathMatchingFilter {
    @Resource
    private ITblSipAcountDimService ISipAccountService;
    @Resource
    private ITblCommDimService ICommService;

    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        String commPassword = WebUtils.toHttp(request).getHeader("commPassword");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        if (commPassword == null) {
            response.getWriter().write(jsonUtil.beanToJsonObject(new JsonRespData("UNAUTHORIZED", -1, "无commPassword信息")));
            return false;
        }
        String commCode = WebUtils.toHttp(request).getHeader("commCode");
        if (commCode == null) {
            response.getWriter().write(jsonUtil.beanToJsonObject(new JsonRespData("UNAUTHORIZED", -1, "无commCode参数")));
            return false;
        } else {
            TblCommDimBo bo = ICommService.findTblCommDimByCommCode(commCode);
            if (!commPassword.equals(bo.getCommPassword())) {
                response.getWriter().write(jsonUtil.beanToJsonObject(new JsonRespData("UNAUTHORIZED", -1, "小区密码不对！")));
                return false;
            }
            if (ISipAccountService.isUserExist(commCode + "_LocalServer") == null) {
                response.getWriter().write(jsonUtil.beanToJsonObject(new JsonRespData("UNAUTHORIZED", -1, "该小区无本地服务器！")));
                return false;
            }
        }
        return true;
    }
}
